package com.shundr.shipper;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.shundr.shipper.base.BaseFragment;
import com.shundr.shipper.cargo.CargoTemplateActivity;
import com.shundr.shipper.common.AboutActivity;
import com.shundr.shipper.common.FavoriteListActivity;
import com.shundr.shipper.common.HistoryListActivity;
import com.shundr.shipper.common.SettingActivity;
import com.shundr.shipper.common.SystemSmsActivity;
import com.shundr.shipper.frame.constant.LContext;
import com.shundr.shipper.order.OrderListActivity;
import com.shundr.shipper.truck.FamTruckListActivity;
import com.shundr.shipper.user.LoginActivity;
import com.shundr.shipper.user.UserInfoActivity;
import com.shundr.shipper.user.http.UserRequest;
import com.shundr.shipper.user.model.UserInfo;
import com.shundr.shipper.user.util.UserListener;
import com.shundr.shipper.user.util.UserUtil;
import com.umeng.soexample.widget.CustomShareBoard;

/**
 * 个人中心 UserInfoFragment
 * 
 * @author larry 2015-4-14 上午11:45:59
 * @version 1.0.0
 * 
 */
public class UserInfoFragment extends BaseFragment implements OnClickListener,UserListener{
	private RelativeLayout mLayoutUser;
	private ImageView ivHead;
	private ImageView ivStatus;
	
	private TextView tvFlag;
	private TextView tvName;
	
	private LinearLayout llCollection;//收藏
	private LinearLayout llMyOrder;//订单
	private TextView tvCollection;//收藏
	private TextView tvMyOrder;//订单
	
	private LinearLayout llRouteSetting;//路线
	private LinearLayout llTruck;//车辆
	private LinearLayout llHistory;//历史
	
	private LinearLayout llSystemMessage;//消息
	private LinearLayout llShare;//分享
	private LinearLayout llSetting;//设置
	private LinearLayout llAbout;//关于
	
	private DisplayImageOptions mOptions;
	
	@SuppressLint("HandlerLeak")
	Handler mHandler=new Handler() {

		@Override
		public void handleMessage(Message msg) {
			try {
				switch (msg.what) {
				case UserRequest.GET_USER_DETAIL_INFO_SUCCESSED:
					UserInfo mUserInfo = (UserInfo) msg.obj;
					UserUtil.saveUserToLocal(mContext, mUserInfo, null);
					onRefresh();
					break;
//				case LHttpRequest.REQUEST_FAILED:
//					ProgressDialogHelper.dismiss();	
//					String description=(String)msg.obj;
//					ToastHelper.toastShort(mContext, description);
//					break;
				default:
					break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			super.handleMessage(msg);
		}
	};

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initOptions();
		onRefresh();
		UserUtil.mUserListeners.add(this);
//		onRefresh();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_user_info, null);
		mLayoutUser = (RelativeLayout)view.findViewById(R.id.layout_user);
		mLayoutUser.setOnClickListener(this);
		ivHead = (ImageView)view.findViewById(R.id.iv_head);
		ivHead.setOnClickListener(this);
		ivStatus = (ImageView)view.findViewById(R.id.iv_auth_status);
//		ivArrow = (ImageView)view.findViewById(R.id.iv_auth_status);
		tvFlag = (TextView)view.findViewById(R.id.tv_flag);
		tvName = (TextView)view.findViewById(R.id.tv_name);
		llCollection = (LinearLayout)view.findViewById(R.id.layout_collection);
		llMyOrder = (LinearLayout)view.findViewById(R.id.layout_order);
		tvCollection = (TextView) view.findViewById(R.id.tv_collection);
		tvMyOrder=(TextView)view.findViewById(R.id.tv_order);
		llCollection.setOnClickListener(this);
		llMyOrder.setOnClickListener(this);
		tvCollection.setOnClickListener(this);
		tvMyOrder.setOnClickListener(this);
		
		llRouteSetting = (LinearLayout) view.findViewById(R.id.layout_route);
		llTruck = (LinearLayout) view.findViewById(R.id.layout_truck);
		llHistory = (LinearLayout) view.findViewById(R.id.layout_history);
		llRouteSetting.setOnClickListener(this);
		llTruck.setOnClickListener(this);
		llHistory.setOnClickListener(this);
		
		llSystemMessage = (LinearLayout) view.findViewById(R.id.layout_message);
		llShare = (LinearLayout) view.findViewById(R.id.layout_share);
		llSetting = (LinearLayout) view.findViewById(R.id.layout_setting);
		llAbout = (LinearLayout) view.findViewById(R.id.layout_about);
		llSystemMessage.setOnClickListener(this);
		llShare.setOnClickListener(this);
		llSetting.setOnClickListener(this);
		llAbout.setOnClickListener(this);
		initOptions();
		return view;
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		UserUtil.mUserListeners.remove(this);
		releaseImageView(ivHead);
		releaseImageView(ivStatus);
	}

	@Override
	public void onResume() {
		if (LContext.isLogin())
			new UserRequest(mContext, mHandler).getUserInfoByToken();
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.layout_user:
			if(LContext.isLogin()){
				intent = new Intent(getActivity(), UserInfoActivity.class);
				startActivity(intent);
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.iv_head:
			if(LContext.isLogin()){
				intent = new Intent(getActivity(), UserInfoActivity.class);
				startActivity(intent);
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.btn_login:
			startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			break;
		case R.id.layout_collection:
			if(LContext.isLogin()){
				startActivity(new Intent(getActivity(), FavoriteListActivity.class));
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.layout_order:
			if(LContext.isLogin()){
				intent = new Intent(getActivity(), OrderListActivity.class);
				startActivity(intent);
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.tv_collection:
			if(LContext.isLogin()){
				startActivity(new Intent(getActivity(), FavoriteListActivity.class));
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.tv_order:
			if(LContext.isLogin()){
				intent = new Intent(getActivity(), OrderListActivity.class);
				startActivity(intent);
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.layout_route:
			if(LContext.isLogin()){
				intent = new Intent(getActivity(), CargoTemplateActivity.class);
				startActivity(intent);
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.layout_truck:
			if(LContext.isLogin()){
				intent = new Intent(getActivity(), FamTruckListActivity.class);
				startActivity(intent);
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.layout_history:
			if(LContext.isLogin()){//历史
				intent = new Intent(getActivity(), HistoryListActivity.class);
				startActivity(intent);
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.layout_message:
			if(LContext.isLogin()){
				intent = new Intent(getActivity(), SystemSmsActivity.class);
				startActivity(intent);
			}else{
				startActivityForResult(new Intent(getActivity(), LoginActivity.class), 500);
			}
			break;
		case R.id.layout_share:
			CustomShareBoard shareBoard = new CustomShareBoard(getActivity());
	        shareBoard.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
			break;
		case R.id.layout_setting:
			startActivityForResult(new Intent(getActivity(), SettingActivity.class),777);
			break;
		case R.id.layout_about:
			intent = new Intent(getActivity(), AboutActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
		
	}
	
	/**
	 * 更新界面
	 * onRefresh(这里用一句话描述这个方法的作用)
	 * (这里描述这个方法适用条件 – 可选)
	 * void
	 * @exception
	 * @since  1.0.0
	 */
	private void onRefresh(){
		if(LContext.isLogin()){
			tvFlag.setVisibility(View.INVISIBLE);
			tvName.setVisibility(View.VISIBLE);
			tvName.setText(LContext.userInfo.getUserPhone());
//			int status = LContext.userInfo.getCompanyValidationStatus();
			if (LContext.getUserValidationStatus() == -1) {//未认证
				ivStatus.setBackgroundResource(R.drawable.iv_validation_fail);
			}else{
				ivStatus.setBackgroundResource(R.drawable.iv_validation_success);
			}
//			switch (status) {
//			case 0:
//				ivStatus.setBackgroundResource(R.drawable.ic_auth_no);
//				break;
//			case 1:
//				ivStatus.setBackgroundResource(R.drawable.ic_auth_ing);
//				break;
//			case 2:
//				ivStatus.setBackgroundResource(R.drawable.ic_auth_ok);
//				break;
//			case 3:
//				ivStatus.setBackgroundResource(R.drawable.ic_auth_fail);
//				break;
//
//			default:
//				break;
//			}
			ivStatus.setVisibility(View.VISIBLE);
			String headUrl=LContext.userInfo.getUserHeadPic();
			ImageLoader.getInstance().displayImage(headUrl, ivHead,mOptions);
		}else{
			tvFlag.setVisibility(View.VISIBLE);
			tvName.setVisibility(View.INVISIBLE);
			ivStatus.setVisibility(View.INVISIBLE);
			ivHead.setImageResource(R.drawable.iv_head);
		}
	}

	@Override
	public void onUserChanged(int flag) {
		onRefresh();
	}
	
	
	@SuppressWarnings("deprecation")
	private void initOptions(){
		mOptions = new DisplayImageOptions.Builder()  
		.showImageForEmptyUri(R.drawable.iv_head)//设置图片Uri为空或是错误的时候显示的图片  
		.showImageOnFail(R.drawable.iv_head)  
		.cacheInMemory(true) //设置图片加载/解码过程中错误时候显示的图片  
		.cacheInMemory(true)//设置下载的图片是否缓存在内存中  
		.cacheOnDisc(true)//设置下载的图片是否缓存在SD卡中  
		.considerExifParams(true)  
		.imageScaleType(ImageScaleType.EXACTLY_STRETCHED)//设置图片以如何的编码方式显示  
		.bitmapConfig(Bitmap.Config.RGB_565)//设置图片的解码类型//  
//		.decodingOptions(Options decodingOptions)//设置图片的解码配置  
		.considerExifParams(true)//设置图片下载前的延迟  
		//.delayBeforeLoading(int delayInMillis)//int delayInMillis为你设置的延迟时间  
		//设置图片加入缓存前，对bitmap进行设置  
		//.preProcessor(BitmapProcessor preProcessor)  
//		.resetViewBeforeLoading(true)//设置图片在下载前是否重置，复位  
		.displayer(new RoundedBitmapDisplayer(45))//是否设置为圆角，弧度为多少  
//		.displayer(new FadeInBitmapDisplayer(100))//是否图片加载好后渐入的动画时间  
		.build();//构建完成  
	}

	@Override
	public void onDestroyView() {
		mHandler.removeCallbacksAndMessages(null);
		super.onDestroyView();
	}
	
}
